package java_class_work.week08.demo4;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author Tiam
 * @Date 2022/10/31 10:33
 * @Description:
 */
public class Ticket implements Runnable {
    private int ticket = 20;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        // 线程不安全
        /*while (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + " 卖出了" + ticket + "号票,剩余" + --ticket);
        }*/

        // 方式一: 线程安全
        /*while (true) {
            // 同步锁, 使其同时只能有一个线程执行, this当前对象Ticket类
            synchronized (this) {
                if (this.ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + " 卖出了" + this.ticket + "号票,剩余" + --this.ticket);
                } else {
                    break;
                }
            }
        }*/

        // 方式三: 加锁
        while (true) {
            // 代码块锁
            lock.lock();
            try {
                if (this.ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + " 卖出了" + this.ticket + "号票,剩余" + --this.ticket);
                } else {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }


    /**
     * 方式二:
     * 线程同步方法 synchronized关键字
     */
    private synchronized void saleTicket() {

    }
}